//
//  RBHttpNetworkHelper.m
//  RMMaterialRed
//
//  Created by XBWH on 2024/3/6.
//

#import "RBHttpNetworkHelper.h"
#import "AFNetworkActivityIndicatorManager.h"

static NSMutableArray *_allSessionTask;
static AFHTTPSessionManager *_sessionManager;

@implementation RBHttpNetworkHelper
+ (NSMutableArray *)allSessionTask {
    if (!_allSessionTask) {
        _allSessionTask = [[NSMutableArray alloc] init];
    }
    return _allSessionTask;
}
+ (void)initialize {
    _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.requestSerializer.timeoutInterval = 30;
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"aRBlication/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}

+ (void)setAFHTTPSessionManagerProperty:(void (^)(AFHTTPSessionManager *))sessionManager {
    sessionManager ? sessionManager(_sessionManager):nil;
}
+ (void)setRequestSerializer:(RBRequestSerializer)requestSerializer {
    _sessionManager.requestSerializer = requestSerializer==RBRequestSerializerHTTP ? [AFHTTPRequestSerializer serializer] : [AFJSONRequestSerializer serializer];
}
+ (void)setResponseSerializer:(RBResponseSerializer)responseSerializer {
    _sessionManager.responseSerializer = responseSerializer==RBResponseSerializerHTTP ? [AFHTTPResponseSerializer serializer] : [AFJSONResponseSerializer serializer];
}
+ (void)setRequestTimeoutInterval:(NSTimeInterval)time {
    _sessionManager.requestSerializer.timeoutInterval = time;
}
+ (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
    [_sessionManager.requestSerializer setValue:value forHTTPHeaderField:field];
}
+ (void)openNetworkActivityIndicator:(BOOL)open {
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:open];
}
+ (void)setSecurityPolicyWithCerPath:(NSString *)cerPath validatesDomainName:(BOOL)validatesDomainName {
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = validatesDomainName;
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
    [_sessionManager setSecurityPolicy:securityPolicy];
    
}
///GET请求
+ (NSURLSessionTask *)GET:(NSString *)URL
                        parameters:(id)parameters
                           success:(RBHttpRequestSuccess)success
                           failure:(RBHttpRequestFailed)failure
{
    NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[self allSessionTask] removeObject:task];
        success ? success(responseObject) : nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData * data=
        error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if ([data isKindOfClass:[NSData class]]) {
            NSDictionary * dict =
            [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSInteger code = [dict[@"code"] integerValue];
            if (code==401) {
                //清除缓存
                [[RBLogInAndOutTool shareInstance] rb_logout];
                [[RBLogInAndOutTool shareInstance] rb_clearCache];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RBlogOutSuccess" object:nil];
                [[RBOneKeyLogin shareInstance] rb_startLoginWithControllerType:RBOneKeyLoginVcTypeTopVc tabBarItemSelectIndex:0 otherSource:nil];
            }
        }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    
    }];
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}
///POST请求
+ (NSURLSessionTask *)POST:(NSString *)URL
                         parameters:(id)parameters
                            success:(RBHttpRequestSuccess)success
                            failure:(RBHttpRequestFailed)failure
{
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[self allSessionTask] removeObject:task];
        success ? success(responseObject) : nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData * data=
        error.userInfo[@"com.alamofire.serialization.response.error.data"];
        if ([data isKindOfClass:[NSData class]]) {
            NSDictionary * dict =
            [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSInteger code = [dict[@"code"] integerValue];
            if (code==401) {
                //清除缓存
                [[RBLogInAndOutTool shareInstance] rb_logout];
                [[RBLogInAndOutTool shareInstance] rb_clearCache];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RBlogOutSuccess" object:nil];
                [[RBOneKeyLogin shareInstance] rb_startLoginWithControllerType:RBOneKeyLoginVcTypeTopVc tabBarItemSelectIndex:0 otherSource:nil];
            }
        }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}
@end
